package net.bplaced.streetfighter;

import net.bplaced.streetfighter.lib.async.task.CommentPostTask;
import net.bplaced.streetfighter.lib.model.Comment;
import net.bplaced.streetfighter.lib.utils.CallBack;
import net.bplaced.streetfighter.lib.utils.RuntimeData;
import net.bplaced.streetfighter.lib.utils.RuntimeDataKey;
import net.bplaced.streetfighter.lib.utils.ServiceReturnPackage;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * @author Sebastian Hoffmann <bo.hoffi@googlemail.com>
 */
public class ReplyToCommentActivity
        extends Activity {

    private Comment commentToReplyTo;
    private Comment reply;

    private EditText authorName;
    private EditText commentEntry;

    private boolean isValid = true;

    private final static String APP_PREFERENCES_KEY = "net.bplaced.streetfighter.preferences";
    private SharedPreferences appPreferences;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        this.appPreferences =
                this.getSharedPreferences(ReplyToCommentActivity.APP_PREFERENCES_KEY, Context.MODE_PRIVATE);

        final Intent i = this.getIntent();
        final Bundle b = i.getExtras();
// this.commentToReplyTo = (Comment) b.getParcelable(Comment.INTENTKEY_COMMENT);

        this.commentToReplyTo = (Comment) RuntimeData.getInstance().get(RuntimeDataKey.COMMENT).getData();

        this.setContentView(R.layout.reply);

        this.authorName = (EditText) this.findViewById(R.id.reply_to_comment_name);
        this.commentEntry = (EditText) this.findViewById(R.id.reply_to_comment_text);

        // Läd den gespeicherten Usernamen, sonst leer
        this.authorName.setText(this.appPreferences.getString(ReplyToCommentActivity.USERNAME_KEY, ""));

        final Button postCommentBtn = (Button) this.findViewById(R.id.reply_to_comment_post);
        postCommentBtn.setOnClickListener(this.postCommentListener);
    }

    /**
     * Deklariert einen Callback, welcher zum Ende des Serviceaurufes aufgerufen wird.
     */
    private final CallBack<ServiceReturnPackage<String>> onFinishedLoading =
            new CallBack<ServiceReturnPackage<String>>() {

                @Override
                public void callbackAction(ServiceReturnPackage<String> result) {

                    if (result != null) {
                        if (result.getErrorMessage() != null) {

                            Toast.makeText(ReplyToCommentActivity.this, result.getErrorMessage(), Toast.LENGTH_SHORT)
                                    .show();

                        } else {

                            ReplyToCommentActivity.this.finish();
                        }
                    }
                };
            };

    private final View.OnClickListener postCommentListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            ReplyToCommentActivity.this.isValid = true;

            if (ReplyToCommentActivity.this.authorName.getText().length() == 0) {
                ReplyToCommentActivity.this.isValid = false;
                ReplyToCommentActivity.this.authorName.setError(ReplyToCommentActivity.this.getResources().getString(
                        R.string.reply_to_comment_duty_text_name));
            }

            if (ReplyToCommentActivity.this.commentEntry.getText().length() == 0) {
                ReplyToCommentActivity.this.isValid = false;
                ReplyToCommentActivity.this.commentEntry.setError(ReplyToCommentActivity.this.getResources().getString(
                        R.string.reply_to_comment_duty_text_entry));
            }

            if (ReplyToCommentActivity.this.isValid) {

                ReplyToCommentActivity.this.reply = new Comment();
                ReplyToCommentActivity.this.reply.author = ReplyToCommentActivity.this.authorName.getText().toString();
                ReplyToCommentActivity.this.reply.authorEmail = "";
                ReplyToCommentActivity.this.reply.authorUrl = "";
                ReplyToCommentActivity.this.reply.authorIp = "192.1.1.128";
                ReplyToCommentActivity.this.reply.commentText =
                        ReplyToCommentActivity.this.commentEntry.getText().toString();
                ReplyToCommentActivity.this.reply.parentComment = ReplyToCommentActivity.this.commentToReplyTo.id;

                ReplyToCommentActivity.this.checkSavedUserName();
            }
        }
    };

    private void postComment() {

        final CommentPostTask task =
                new CommentPostTask(this, this.getResources().getString(R.string.reply_to_comment_progress_message),
                        this.onFinishedLoading);
        task.execute(this.reply.author, "", "", this.reply.authorIp, this.reply.commentText,
                this.reply.parentComment.toString());
    }

    private void checkSavedUserName() {

        final String enteredUserName = this.authorName.getText().toString();
        final String savedUserName = this.appPreferences.getString(ReplyToCommentActivity.USERNAME_KEY, "");

        if (!enteredUserName.equals(savedUserName)) {

            this.saveUserName(enteredUserName);

        } else {
            this.postComment();
        }
    }

    private final static String USERNAME_KEY = "REPLY_FORM_USERNAME";

    private void saveUserName(final String userName) {

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.reply_to_comment_dialog_title)
                .setMessage(R.string.reply_to_comment_dialog_message)
                .setPositiveButton(R.string.reply_to_comment_dialog_positive_button,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                final SharedPreferences.Editor editor =
                                        ReplyToCommentActivity.this.appPreferences.edit();
                                editor.putString(ReplyToCommentActivity.USERNAME_KEY, userName);
                                editor.commit();

                                ReplyToCommentActivity.this.postComment();
                            }
                        })
                .setNegativeButton(R.string.reply_to_comment_dialog_negative_button,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                ReplyToCommentActivity.this.postComment();
                            }
                        }).create().show();
    }
}